package com.cgtong.android.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.activity.LoginActivity;
import com.cgtong.android.activity.ProblemDetailActivity;
import com.cgtong.android.adapter.ProblemsAdapter;
import com.cgtong.android.base.BaseLazyFragment;
import com.cgtong.android.bean.FilterBean;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.bean.UserBean;
import com.cgtong.android.callback.DiffCallBack;
import com.cgtong.android.event.LoadUserInfoEvent;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.ProblemPageContract;
import com.cgtong.android.mvp.presenter.ProblemPagePresenter;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.BaseDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static com.cgtong.android.activity.ProblemDetailActivity.KEY_LIST_ITEM_POSITION;


/**
 * 浏览问题
 * Created by chunc on 2017/10/21.
 */

public class BrowseProblemFragment extends BaseLazyFragment implements ProblemPageContract.View {

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.search_bar_fl)
    FrameLayout mSearchBarFl;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout mSwipeLayout;
    @BindView(R.id.filter_edt)
    EditText mSearchEdt;
    @BindView(R.id.clear_img)
    ImageView mClearImg;
    @BindView(R.id.search_bar_ll)
    LinearLayout mSearchBarLl;
    @BindView(R.id.back_top_img)
    ImageView mBackTopImg;

    private ArrayList<ProblemBean> mList;
    private ArrayList<ProblemBean> mNewList;
    private ProblemsAdapter mAdapter;

    private ProblemPageContract.Presenter mPresenter;
    private int mStatus = 0;//时效状态
    private int mIsExpired = 0;//受理状态
    private String mLatitudeValue = "null";//经度
    private String mLongitudeValue = "null";//纬度
    private String mSearchKey = "";

    //时间范围
    private String mBeginTime = "";
    private String mEndTime = "";

    public static BrowseProblemFragment newInstance() {
        Bundle args = new Bundle();
        BrowseProblemFragment fragment = new BrowseProblemFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_browse_problem;
    }

    @Override
    public void initData() {
        mPresenter = new ProblemPagePresenter(this);
        mList = new ArrayList<>();
        mNewList = new ArrayList<>();
        initRecyclerView();

        //搜索栏失去焦点监听
//        mSearchEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                LogUtils.d("hasFocus = " + hasFocus);
//                if (hasFocus) {
//
//                } else {
//
//                }
//            }
//        });
        //回车键搜索监听
        mSearchEdt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mSearchEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mSearchKey = mSearchEdt.getText().toString();
                    mPresenter.httpProblemsData("", mSearchKey, 0, mStatus, mIsExpired, mLatitudeValue, mLongitudeValue, mBeginTime, mEndTime, true);
                    KeyboardUtils.hideSoftInput(mSearchEdt);
                    return false;
                }
                return false;
            }
        });
        //显示或隐藏清空按钮
        mSearchEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mClearImg.setVisibility(View.GONE);
                    mSearchKey = "";
//                    loadDataByNet();
                } else {
                    mClearImg.setVisibility(View.VISIBLE);
                }
            }
        });
        //滑动时不加载图片
        mRecyclerView.addOnScrollListener(mOnScrollListener);
    }

    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
//            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                GlideApp.with(getActivity()).resumeRequests();
//            } else {
//                GlideApp.with(getActivity()).pauseRequests();
//            }
           LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            if( linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0){
                mBackTopImg.setVisibility(View.GONE);
            }else{
                mBackTopImg.setVisibility(View.VISIBLE);
            }
        }
    };


    @Override
    protected void loadDataByNet() {
        mPresenter.httpProblemsData("", mSearchKey, 0, mStatus, mIsExpired, mLatitudeValue, mLongitudeValue, mBeginTime, mEndTime, true);
    }

    @Override
    protected void onDataReloadByNet(View v) {
        mSearchKey = "";
        mPresenter.httpProblemsData("", mSearchKey, 0, mStatus, mIsExpired, mLatitudeValue, mLongitudeValue, mBeginTime, mEndTime,true);
    }

//    public void loadDataByFilter(int status, int isExpired, String latitude, String longitude) {
//        mStatus = status;
//        mIsExpired = isExpired;
//        mLatitudeValue = latitude;
//        mLongitudeValue = longitude;
//        LogUtils.d("status = " + status + " isExpired = " + isExpired + " latitude = " + latitude + " longitude = " + longitude);
//        loadDataByNet();
//    }

    /**
     * 初始化列表
     */
    private void initRecyclerView() {
        mSwipeLayout.setColorSchemeResources(R.color.color_scheme);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.httpProblemsData("", mSearchKey, 0, mStatus, mIsExpired, mLatitudeValue, mLongitudeValue, mBeginTime, mEndTime, true);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new ProblemsAdapter(mList, getActivity());
        mRecyclerView.setAdapter(mAdapter);
//        mRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, R.drawable.shape_horizontal_divider));
//        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        //跳转详情
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                ProblemBean problemBean = mAdapter.getItem(position);
                LogUtils.d("problemBean: " + problemBean.toString());
                boolean canDelete = false;
                boolean canEvaluate = false;
                if (((App) getActivity().getApplicationContext()).isUserLogin()) {
                    if ((problemBean.getStatus() == 4 || problemBean.getStatus() == 5 || problemBean.getStatus() == 7) && App.getInstance().isOwnself(problemBean.getCreateUserId())) {
                        canDelete = true;
                    }
                    if ((problemBean.getStatus() == 4 || problemBean.getStatus() == 5) && App.getInstance().isOwnself(problemBean.getCreateUserId())) {
                        canEvaluate = true;
                    }
                }
                ProblemDetailActivity.startForResult(BrowseProblemFragment.this, problemBean.getId(), canDelete, canEvaluate, position);
//                ProblemDetailActivity.start(getActivity(), problemBean.getId(), canDelete, canEvaluate);
            }
        });
        //关注用户
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (((App) getContext().getApplicationContext()).isUserLogin()) {
                    long userId = mAdapter.getItem(position).getCreateUserId();
                    if (App.getInstance().isOwnself(userId)) {
                        ToastUtils.showShort(getString(R.string.txt_cannot_follow_youself));
                        return;
                    }
                    mPresenter.follow(mAdapter.getItem(position).getCreateUserId(), position);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivityForResult(intent, ConstantManager.REQUEST_LOGIN_CODE);
                }
            }
        });
//        mAdapter.setLoadMoreView(new CustomLoadMoreView());
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                String maxTime = mAdapter.getItem(mAdapter.getItemCount() - 2).getCreateTime();
                mPresenter.httpProblemsData(maxTime, mSearchKey, 0, mStatus, mIsExpired, mLatitudeValue, mLongitudeValue, mBeginTime, mEndTime, false);

            }
        }, mRecyclerView);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.d("requestCode:" + requestCode + " resultCode:" + resultCode + " data:" + (data != null ? data.toString() : "null"));
        if (resultCode == RESULT_OK) {
            if (requestCode == ProblemDetailActivity.KEY_CODE_FOLLOW_PROBLEM) {
                int position = data.getIntExtra(KEY_LIST_ITEM_POSITION, -1);
                LogUtils.d("onActivityResult = " + position);
                if (position != -1) {
                    mAdapter.remove(position);
                    if (mAdapter.getItemCount() == 0) {
                        mAdapter.setNewData(null);
                        mAdapter.setEmptyView(R.layout.layout_empty);
                    }
                }
            }
        }
    }

    @OnClick({R.id.search_bar_fl, R.id.clear_img,R.id.back_top_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_bar_fl:
                mSearchBarLl.setVisibility(View.VISIBLE);
                mSearchBarFl.setVisibility(View.GONE);
                KeyboardUtils.showSoftInput(mSearchEdt);
                break;
            case R.id.clear_img:
                mSearchKey = "";
                mSearchEdt.setText("");
                KeyboardUtils.hideSoftInput(mSearchEdt);
                loadDataByNet();
                break;
            case R.id.back_top_img:
//                mRecyclerView.scrollToPosition(0);
                goToTop();
                mBackTopImg.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    protected void goToTop() {
        mRecyclerView.stopScroll();
        LinearLayoutManager mLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        mLayoutManager.setSmoothScrollbarEnabled(true);
        int firstVisibilityPosition = mLayoutManager.findFirstVisibleItemPosition();
        if (firstVisibilityPosition > 10) {
            mLayoutManager.scrollToPositionWithOffset(10, 0);
        }
        mRecyclerView.smoothScrollToPosition(0);
//        firstVisibilityPosition = 0;
    }


    @Override
    public void setRefreshing(boolean isRefresh) {
        if (mSwipeLayout != null) {
            mSwipeLayout.setRefreshing(isRefresh);
        }
    }

    @Override
    public void setEnableLoadMore(boolean enableLoadMore) {
        mAdapter.setEnableLoadMore(enableLoadMore);
    }

    @Override
    public void onLoadMoreEnd(boolean isLoadMoreEnd) {
        mAdapter.loadMoreEnd(isLoadMoreEnd);
    }

    @Override
    public void onHttpProblemsDataSuccess(List<ProblemBean> datas, boolean isRefresh) {
        PostUtil.postSuccessDelayed(loadService);
        if (isRefresh) {
            mNewList.clear();
            mAdapter.setNewData(datas);
            mAdapter.disableLoadMoreIfNotFullPage(mRecyclerView);
        } else {
            mAdapter.addData(datas);
        }
        mNewList.addAll(datas);//比较集合不同的List
        mAdapter.loadMoreComplete();

    }

    @Override
    public void onHttpDraftsSuccess(List<ProblemBean> datas) {

    }


    @Override
    public void onError(ApiException e) {
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_error);
    }


    @Override
    public void onNullData() {
        PostUtil.postSuccessDelayed(loadService);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_empty);
    }

    @Override
    public void onSearchNullData() {
        showSearchNullResultDialog();
    }


    @Override
    public void onFollowSuccess(long id, int position, ApiResult result) {
        LogUtils.d("onfollowsuccess position = " + position + " newlist = " + mNewList.size() + " list = " + mList.size() + " adapter = " + mAdapter.getData().size());
        if (result.getCode() == 0) {
            List<ProblemBean> beanList = mAdapter.getData();
            for (int i = 0; i < beanList.size(); i++) {
                ProblemBean bean = beanList.get(i);
                if (bean.createUserId == id) {
                    ProblemBean newProblemBean = bean.cloneAll(bean);
                    if (newProblemBean.isCreateUserAttention == 1) {
                        newProblemBean.isCreateUserAttention = 0;
                    } else {
                        newProblemBean.isCreateUserAttention = 1;
                    }
                    mNewList.set(i, newProblemBean);
                }
            }
            DiffUtil.DiffResult diffResult = DiffUtil
                    .calculateDiff(new DiffCallBack(mAdapter.getData(), mNewList),
                            false);
            diffResult.dispatchUpdatesTo(mAdapter);

            mAdapter.setAllNewData(mNewList);
            mNewList.clear();
            mNewList.addAll(mAdapter.getData());
        } else {
            ToastUtils.showShort(result.getMsg());
        }
    }

    @Override
    public void onDeleteDraftSuccess(int position, ApiResult result) {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 注册对象
        EventBus.getDefault().register(this);
    }

    /**
     * 【我关注的人】界面取消关注后，更新界面
     *
     */
    @Subscriber(tag = ConstantManager.UPDATE_FOLLOWED_USER_STATUS_TAG)
    private void updateFollowedUserStatus(UserBean userBean) {
        if (userBean != null) {
            long id = userBean.getId();
            LogUtils.d("--------收到更新消息-----------：" + userBean.toString());
            List<ProblemBean> beanList = mAdapter.getData();
            for (int i = 0; i < beanList.size(); i++) {
                ProblemBean bean = beanList.get(i);
                if (bean.createUserId == id) {
                    ProblemBean newProblemBean = bean.cloneAll(bean);
                    if (newProblemBean.isCreateUserAttention == 1) {
                        newProblemBean.isCreateUserAttention = 0;
                    } else {
                        newProblemBean.isCreateUserAttention = 1;
                    }
                    mNewList.set(i, newProblemBean);
                }
            }
            DiffUtil.DiffResult diffResult = DiffUtil
                    .calculateDiff(new DiffCallBack(mAdapter.getData(), mNewList),
                            false);
            diffResult.dispatchUpdatesTo(mAdapter);

            mAdapter.setAllNewData(mNewList);

            mNewList.clear();
            mNewList.addAll(mAdapter.getData());
        }
    }

    /**
     * 登录成功，更新关注状态
     *
     * @param event
     */
    @Subscriber
    private void updateFollowedUserStatus(LoadUserInfoEvent event) {
        LogUtils.d("-------------登录成功，更新关注状态----------------");
        mPresenter.httpProblemsData("", mSearchKey, 0, mStatus, mIsExpired, mLatitudeValue, mLongitudeValue, mBeginTime, mEndTime,true);
    }

    @Override
    public void onDestroy() {
        // 注销
        EventBus.getDefault().unregister(this);
        super.onDestroy();
//        mPresenter.onDestroy();
    }


    /**
     * 接收来自ShowEverybodyFragment的筛选动作
     *
     * @param filter
     */
    @Subscriber(tag = ConstantManager.FILTER_TAG)
    private void doFilter(FilterBean filter) {
        LogUtils.d("doFilter: status = " + filter.getStatus() + " isexpired = " + filter.getIsExpired() + " lat = " + filter.getLat() + " lng = " + filter.getLng());
        mStatus = filter.getStatus();
        mIsExpired = filter.getIsExpired();
        mBeginTime = filter.getBeginTime();
        mEndTime = filter.getEndTime();
        //按要求屏蔽经纬度
//        if (TextUtils.isEmpty(filter.getLat())) {
//            mLatitudeValue = "null";
//        } else {
//            mLatitudeValue = filter.getLat();
//        }
//        if (TextUtils.isEmpty(filter.getLng())) {
//            mLongitudeValue = "null";
//        } else {
//            mLongitudeValue = filter.getLng();
//        }
        loadDataByNet();


    }

    /**
     * 搜索结果为空提示框
     */
    private void showSearchNullResultDialog() {
        BaseDialog.create(getChildFragmentManager())
                .setLayoutRes(R.layout.layout_empty_dialog)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        view.findViewById(R.id.confirm_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.CENTER)
                .setStyle(R.style.CenterDialogTheme)
                .show();
    }


}

